<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <el-card>
          <div slot="header">个人信息</div>
          <div>
            <div style="text-align: center">
              <div class="el-upload">
                <img
                  title="点击上传头像"
                  class="avatar"
                  @click="imagecropperShow = true"
                  alt=""
                  :src="avatar ? baseApi + avatar : imageUrl"
                />
                <my-upload
                  :modelValue.sync="imagecropperShow"
                  field="file"
                  :headers="headers"
                  img-format="png"
                  url="/dev-api/sys/user/uploadImage"
                  @srcFileSet="srcFileSet"
                  @crop-success="cropSuccess"
                  @crop-upload-success="cropUploadSuccess"
                  @crop-upload-fail="cropUploadFail"
                />
              </div>
            </div>
            <ul class="user-info">
              <li>
                <div style="height: 100%">
                  登录账号
                  <div class="user-right">{{ userInfo.username }}</div>
                </div>
              </li>
              <li>
                用户昵称
                <div class="user-right">{{ userInfo.nickName }}</div>
              </li>
              <!-- <li>
                所属部门
                <div class="user-right"></div>
              </li> -->
              <li>
                手机号码
                <div class="user-right">{{ userInfo.phoneNumber }}</div>
              </li>
              <li>
                用户邮箱
                <div class="user-right">{{ userInfo.email }}</div>
              </li>
              <li>
                安全设置
                <div class="user-right">
                  <a @click="updateUserPassword">修改密码</a>
                  <!-- <a @click="$refs.email.dialog = true">修改邮箱</a> -->
                </div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户资料" name="first">
              <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="80px"
                size="mini"
              >
                <el-form-item label="昵称" prop="nickName">
                  <el-input
                    v-model="form.nickName"
                    style="width: 35%"
                  ></el-input>
                  <span style="color: #c0c0c0; margin-left: 10px"
                    >用户昵称不作为登录使用</span
                  >
                </el-form-item>
                <el-form-item label="手机号码" prop="phoneNumber">
                  <el-input
                    v-model="form.phoneNumber"
                    style="width: 35%"
                  ></el-input>
                  <span style="color: #c0c0c0; margin-left: 10px"
                    >手机号码不能重复</span
                  >
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" style="width: 35%"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio v-model="form.sex" label="1">男</el-radio>
                  <el-radio v-model="form.sex" label="0">女</el-radio>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="doSubmit"
                    >保存配置</el-button
                  >
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="second">
              <el-table :data="tableList">
                <el-table-column prop="operate" label="行为" align="center"/>
                <el-table-column prop="ip" label="IP" align="center"/>
                <el-table-column
                  :show-overflow-tooltip="true"
                  prop="ipAddress"
                  label="IP来源"
                  align="center"
                />
                <el-table-column prop="browser" label="浏览器" align="center"/>
                <el-table-column prop="requestTime" label="请求耗时" align="center">
                  <template slot-scope="{row}">
                    <el-tag v-if="row.requestTime.split('m')[0] <= 300" type="success"
                      >{{ row.requestTime }}</el-tag
                    >
                    <el-tag v-else-if="row.requestTime.split('m')[0] <= 1000" type="warning"
                      >{{ row.requestTime }}</el-tag
                    >
                    <el-tag v-else type="danger">{{ row.requestTime }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column align="center">
                  <template slot="header">
                    <div
                      style="
                        display: inline-block;
                        margin-left: 15px; 
                      ">
                      创建日期<i
                      @click="getList()"
                        class="el-icon-refresh"
                        style="margin-left: 5px;cursor: pointer;"
                      />
                    </div>
                  </template>
                  <template slot-scope="scope">
                    <span>{{ new Date(scope.row.createTime).toLocaleDateString()}}</span>
                  </template>
                </el-table-column>
              </el-table>
              <Pagination :total="total" @pagination="handlePage"></Pagination>
            </el-tab-pane>
          </el-tabs>
          <!-- <div slot="header">用户资料</div> -->
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="25%">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        class="demo-ruleForm"
        inline
        size="mini"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="旧密码" prop="oldPass">
              <el-input
                v-model="ruleForm.oldPass"
                type="password"
                autocomplete="on"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="新密码" prop="newPass">
              <el-input
                type="password"
                v-model="ruleForm.newPass"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="checkPass">
              <el-input
                type="password"
                v-model="ruleForm.checkPass"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpdatePass">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateUser, list } from "@/api/system-setup/user-management";
import { mapGetters } from "vuex";
import "babel-polyfill";
import myUpload from "vue-image-crop-upload";
import { getToken, session } from "@/utils/auth";
export default {
  components: {
    "my-upload": myUpload,
  },
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.newPass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      total:0,
      activeName: "first",
      dialogVisible: false,
      imageUrl: require("../../assets/images/defaultUser.png"),
      imagecropperShow: false,
      headers: {
        Token: getToken(),
      },
      ruleForm: {
        oldPass: "",
        newPass: "",
        checkPass: "",
      },
      rules: {
        newPass: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "长度在 6 到 11 个字符",
            trigger: "blur",
          },
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        oldPass: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: "blur",
          },
        ],
      },
      form: {
        id: session.get("id"),
        username: "",
        password: "",
        nickName: "",
        phoneNumber: "",
        email: "",
        sex: "1",
      },
      tableList: [],
      pageInfo: {
        pageNum: 0,
        pageSize:10
      }
    };
  },
  computed: {
    ...mapGetters(["avatar", "baseApi", "userInfo"]),
  },
  created() {
    this.$store
      .dispatch("user/getInfo", { id: session.get("id") })
      .then((res) => {
        const { nickName, phoneNumber, email, sex, username, password } = res.data.sysUser;
        this.form.nickName = nickName;
        this.form.phoneNumber = phoneNumber;
        this.form.email = email;
        this.form.sex = sex;
        this.form.username = username;
        this.form.password = password;
      });
    this.getList()
  },
  methods: {
    srcFileSet(fileName, fileType, fileSize) {
      console.log(fileName, fileType, fileSize);
    },
    //上传成功得回调
    async cropUploadSuccess(res, originPicName) {
      if (res.code == 200) {
        this.$store.dispatch("user/getInfo", { id: session.get("id") });
      }
    },
    cropUploadFail() {},
    cropSuccess(imgDataUrl, field) {
      this.imageUrl = imgDataUrl;
    },
    confirmUpdatePass() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await updateUserPwd({
            id: session.get("id"),
            oldPassword: this.ruleForm.oldPass,
            newPassword: this.ruleForm.newPass,
          });
          if (res.code == 200) {
            this.warning("当前用户密码已修改,即将自动退出,请重新登陆！");
            setTimeout(() => {
              this.$store.dispatch("user/logout", "rest").then(() => {
                location.reload(); // 为了重新实例化vue-router对象 避免bug
              });
            }, 1500);
          }
        } else {
          return false;
        }
      });
    },
    updateUserPassword() {
      this.ruleForm = {
        oldPass: "",
        newPass: "",
        checkPass: "",
      }
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    doSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await updateUser(this.form);
          if (res.code == 200) {
            //this.$store.dispatch("user/getInfo", { id: session.get("id") });
          }
        } else {
          return false;
        }
      });
    },
    async getList() {
      let res = await list(this.pageInfo)
      if (res.code == 200) {
        this.tableList = res.data.records
        this.total = res.data.total
      }
    },
    handlePage(val) {
      this.pageInfo.pageNum = val.page
      this.pageInfo.pageSize = val.limit
      this.getList()
    },
    handleClick(tab, event){
      //console.log(tab, event)
    }
  },
};
</script>

<style lang="scss" scope>
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}
.el-upload {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  outline: 0;
}
.user-info {
  padding-left: 0;
  list-style: none;
  li {
    border-bottom: 1px solid #f0f3f4;
    padding: 11px 0;
    font-size: 13px;
  }
  .user-right {
    float: right;
    a {
      color: #317ef3;
    }
  }
}
</style>
